//
//  LoginViewController.m
//  1505BmobDemo
//
//  Created by HeHui on 16/1/7.
//  Copyright (c) 2016年 Hawie. All rights reserved.
//

#import "LoginViewController.h"
#import "MyButton.h"
#import "Tool.h"
#import "RegisterViewController.h"


@interface LoginViewController ()
@property (weak, nonatomic) IBOutlet UITextField *userNameTF;
@property (weak, nonatomic) IBOutlet UITextField *passwordTF;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self checkTextFields];
    
    // Do any additional setup after loading the view.
}

- (IBAction)userNameTFEditingChanged:(UITextField *)sender {
    [self checkTextFields];
}

- (IBAction)passwordEditingChanged:(UITextField *)sender {
    [self checkTextFields];
}

- (void) checkTextFields
{
    if (self.userNameTF.text.length > 0 && self.passwordTF.text.length > 0) {
        self.loginBtn.enabled = YES;
    }else {
        self.loginBtn.enabled = NO;
    }

}

- (IBAction)loginBtnPressed:(UIButton *)sender {
    sender.userInteractionEnabled = NO;
    [SVProgressHUD showWithStatus:@"logging..." maskType:SVProgressHUDMaskTypeClear];
    
    NSString *pwdMDTStr = [Tool MD5StringFromString:self.passwordTF.text];
    
    [BmobUser loginWithUsernameInBackground:self.userNameTF.text password:pwdMDTStr block:^(BmobUser *user, NSError *error) {
        sender.userInteractionEnabled = YES;
        if (user) {
            [SVProgressHUD showSuccessWithStatus:@"登录成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:USER_REFRESH_NOTICE object:nil];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else {
            
            NSString *msg = nil;
            if (error.code == 101) {
                msg = @"账号或密码错误";
            }else  {
            }
            [SVProgressHUD showErrorWithStatus:msg];
        }
    }];
}

- (IBAction)registerClicked:(UIButton *)sender {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    RegisterViewController *registerVC = [sb instantiateViewControllerWithIdentifier:@"RegisterViewController"];
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:registerVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;

}
@end
